package com.hq.common.utils;

import org.springframework.context.ApplicationContext;

import java.util.Collection;
import java.util.Map;

/**
 * @since 2015-02-12 10:50
 */
public final class ApplicationContextUtils {
    private static ApplicationContext ctx;

    private ApplicationContextUtils() {
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) ctx.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return ctx.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return ctx.getBean(name, requiredType);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> type) {
        return ctx.getBeansOfType(type);
    }

    public static <T> Collection<T> getBeanListOfType(Class<T> type) {
        Map map = ctx.getBeansOfType(type);
        if (map.size() >= 1) {
            return map.values();
        }
        return null;
    }

    public static boolean containsBean(String name) {
        return ctx.containsBean(name);
    }

    public static boolean isSingleton(String name) {
        return ctx.isSingleton(name);
    }

    public static Class<?> getType(String name) {
        return ctx.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名，则返回这些别名
     */
    public static String[] getAliases(String name) {
        return ctx.getAliases(name);
    }
}
